/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package helpdiabetesj2me;

import javax.microedition.lcdui.*;
import javax.microedition.lcdui.Font;
import javax.microedition.rms.*;

/**
 *
 * @author Johan
 */
public class ReadItemList extends MyCanvas implements CommandListener {

     static final String[] str_selitems = {"Geselecteerde items"};
     static final String[] str_terug = {"Terug"};
     static final String[] str_kiezen = {"Kiezen"};
     static final String[] str_noitemss = {"Er werden nog geen voedingsmiddelen geselecteerd"};
     static final String[] str_gram = {"gram"};
     static final String[] str_amount_kh = {"gram koolhydraten"};


    //points to the record in selitemsrs that is first shown
    int shownrecid;
    
    //temp variable used in paint()
    int tempid;
    
    private Command Terug;
    private Command Kiezen;
    
    /** Creates a new instance of ReadItemList */
    public ReadItemList(Font userfont, HelpDiabetes midlet) {
         super(userfont,midlet);
         shownrecid = 1;
         //don't need these inherited fields'
         enteredstring = null;
         /*if (flipflopTimer != null) flipflopTimer.cancel();
         flipflopTimer = null;*/

         //class doesn't need a full keyboard

         resetexittimer(this);
         
         Terug = new Command(str_terug[HelpDiabetes.languageIndex],str_terug[HelpDiabetes.languageIndex],Command.EXIT,0);
         this.addCommand(Terug);
         Kiezen = new Command(str_kiezen[HelpDiabetes.languageIndex],str_kiezen[HelpDiabetes.languageIndex],Command.EXIT,0);
         this.setCommandListener(this);
    }

    protected void paint(Graphics graphics) {
                x=0;y=0;
                // here the full screen will be drawn
                
                //first set the font to the one passed to the constructor of GetItemFromUser
                graphics.setFont(userfont);

                //clear the screen 
                graphics.setColor(255,255,255);
                graphics.fillRect(0, 0, scrwidth, scrhght);
                /** Print header */
                paintstring(str_selitems[HelpDiabetes.languageIndex].getBytes(),false,graphics,userfont);
                x=0;y= y+fonthght;
                // a horizontal line under the enteredstring
                graphics.drawLine(0,y,scrwidth,y);
                y=y+1;
               
                try {
                    //first check if recordstore with selected items is already opened
                    if (HelpDiabetes.selitemsrs == null) {
                        //recordstore is not yet opened, need to check first if recordstore exists
                        // if it's not existing then an exception will be thrown - it means there's no recordstore'
                        HelpDiabetes.selitemsrs = RecordStore.openRecordStore("selecteditems",false);
                   }
                    
                   if (HelpDiabetes.selitemsrs.getNumRecords() > 0) {
                       this.addCommand(Kiezen); 
                       //first record to be shown inverted
                       drawitem(true,shownrecid,graphics);
                       //this is to make the line inverted for the whole width of the screen
                       graphics.setColor(0,0,0);
                       graphics.fillRect(x,y,scrwidth-x,fonthght);
                       graphics.setColor(255,255,255);
                       x=0;y=y+fonthght;
                       // no draw next elements normal, if there are any, and as long as screensize not exceeded
                       tempid = shownrecid + 1;
                       while (tempid < (HelpDiabetes.selitemsrs.getNumRecords() + 1) & (y < scrhght)) {
                           drawitem(false,tempid,graphics);
                           x=0;y=y+fonthght;
                           tempid++;
                       }
                   } else {
                        this.removeCommand(Kiezen);
                        paintstring(str_noitemss[HelpDiabetes.languageIndex].getBytes(),false,graphics,userfont);
                   }
                   //method defined in parent class

               } catch (RecordStoreNotOpenException ex1) {
                   this.removeCommand(Kiezen);
                    paintstring(str_noitemss[HelpDiabetes.languageIndex].getBytes(),false,graphics,userfont);
               } catch (RecordStoreNotFoundException ex3) {
                   this.removeCommand(Kiezen);
                    paintstring(str_noitemss[HelpDiabetes.languageIndex].getBytes(),false,graphics,userfont);
               } catch (Exception ex2) {
                     
                    (new ReportException()).Report("Exception in ReadItemList.paint",ex2,false);
               } 
                
    }
    
    //method used in paint function
    //invert true means text to be drawn inverted
    //returnvalue 
    void drawitem(boolean invert,int recid,Graphics graphics) {
        String amount1;
        int unit1;
        int i2;
        int recid1;
        int i1=0;
        int unitnumber;
        try {
           //read the record from list with selected items 
           blength = HelpDiabetes.selitemsrs.getRecord(recid,b,0);
        
           // first get recid1, and amount
           i1 = getfirstsemicolon();
           recid1 = Integer.parseInt(new String(b,0,i1));
           i2 = getnextsemicolon();
           amount1 = new String(b,i1+1,i2-i1-1);
           
           // now get the unitnumber
           i1 = i2;
           i2 = blength;
           unitnumber = Integer.parseInt(new String(b,i1+1,i2-i1-1),10);
             
           
           //now read the food item details
           blength = FoodFile.getRecord(recid1,b,0);
           
           
           
           //from the recordstore, we need to get the unit
           //we need to skip a few columns in the food record store (with columns referring to the columns used in excel, depending on the value of unitnumber
           i1 = getfirstsemicolon();
           for (int itemp = 1;itemp < unitnumber;itemp++) {
                i2=getnextsemicolon();i2=getnextsemicolon();i2=getnextsemicolon();i2=getnextsemicolon();i2=getnextsemicolon();i2=getnextsemicolon();
                i1=i2;
           }
           
           i2 = getnextsemicolon();
           units[8] = new String(b,i1+1,i2-i1-1);
           try {
               unit1 = Integer.parseInt(units[8]);
           } catch (NumberFormatException ex) {
               unit1 = 8;
           }
           
           //I need to check first if unit is 100 gram or 100 ml, if so change the unit to gram and ml respectively
           switch (unit1) {
                case 17: //unit is 100 gr, change to gram
                    unit1 = 1;
                    break;
                case 18: //unit is 100 ml, change to ml
                    unit1 = 21;
                    break;
               default:;
           }
           
           //now paint the complete string consisting of amount, unitname and itemtext
           if (units[unit1].indexOf("=") > -1)
               paintstring((
                       amount1 +
                       " " +
                       units[unit1].substring(0,units[unit1].indexOf("=")) +
                       " "
                       ).getBytes(),invert,graphics,userfont);
           else
               paintstring((
                       amount1 +
                       " " +
                       units[unit1] +
                       " "
                       ).getBytes(),invert,graphics,userfont);

           paintstring(b,blength,invert,graphics,userfont);
           //added 16/06 to show amount of carbs for each item between brackets
           CalculateAmounts_in_b(unitnumber);
           paintstring(  (" (" + Float.Int((Float.parse(amount1,10)).Mul(koolh).Mul(10).Add(new Float(5,-1))).Div(10) + " " + str_amount_kh[HelpDiabetes.languageIndex] + ")").getBytes(),invert,graphics,userfont);

           
           
        } catch (NumberFormatException nrforex) {// added june 2009, for support of own food items. If numberformatexception, it means the parseInt of recid1 failed, so it's a text
               // the exception occurred at statement recid1 = Integer.parseInt(new String(b,0,i1));
               // so we continue from there
            String fooditemname = new String(b,0,i1);
            i2 = getnextsemicolon();
            int percentage = Integer.parseInt(new String(b,i1+1,i2-i1-1),10);
            i1 = i2;
            i2 = blength;
            int amount = Integer.parseInt(new String(b,i1+1,i2-i1-1));
            paintstring ( (
                 amount + " "
                 + str_gram[HelpDiabetes.languageIndex]
                 + " "
                 + fooditemname
                 + " ("
                 + (new Float((long)amount)).Mul((long)percentage).Div(100).toString()
                 + " "
                 + str_amount_kh[HelpDiabetes.languageIndex]
                 + ")"
                    ).getBytes(),invert,graphics,userfont);
        } catch (InvalidRecordIDException iex) {
            ;
        }
        catch (Exception e) {
            (new ReportException()).Report("Exception in ReadItemList.drawitem",e,false);
        }
    }
    
    //the method that will be called to show the list
    void showlist() {
        shownrecid = 1;
        curdisp = midlet.getDisplay().getCurrent();
        midlet.getDisplay().setCurrent(this);
        //resetflipfloptimer(this);
        //setscrsize();
        repaint();    
    }

    public void commandAction(Command command, Displayable displayable) {
        resetexittimer(this);
        if (command == Terug) {
            resetflipfloptimer(curdisp);
            midlet.getDisplay().setCurrent(curdisp);
        } else if (command == Kiezen) {
            keyPressed(getKeyCode(FIRE));
        }
    }
    
    //will be used to check if user presses up or down key, in order to scroll through the list
    public synchronized void keyPressed (int keyCode) {
        int unitnumber;
        int unit1;
        int i2;
        int recid1;
        int i1=0;
        String oldamount;
            resetexittimer(this);
         switch(getGameAction(keyCode)) {
             case UP:
                    if (shownrecid > 1) {
                        shownrecid--;
                        repaint();
                    }
                    break;
             case DOWN:
                    try {
                        if (shownrecid < HelpDiabetes.selitemsrs.getNumRecords()) {
                            shownrecid++;
                            repaint();
                        }
                    } catch (RecordStoreNotOpenException ex) {
                        (new ReportException()).Report("Exception in keypressed",ex,false);
                    }
                    break;
             case FIRE:
                    if (HelpDiabetes.selitemsrs != null) {
                        try {
                            if (HelpDiabetes.foodrs.getNumRecords() > 0) {
                                   //first read recid and amount from the list that holds the selected fooditems
                                   blength = HelpDiabetes.selitemsrs.getRecord(shownrecid,b,0);
                                   i1 = getfirstsemicolon();
                                   recid1 = Integer.parseInt(new String(b,0,i1));
                                   i2 = getnextsemicolon();
                                   oldamount = new String(b,i1+1,i2-i1-1);
                                   i1=i2;
                                   i2 = blength;
                                   unitnumber = Integer.parseInt(new String(b,i1+1,i2-i1-1));
                                   // now get the contents of the foodrecord, just for the sake of getting the unit1
                                   //NOTE 2/11/2008 :
                                   //It's only necessary for older versions of the foodtable to try to parse the unit. In practice
                                   // it will always be a string, so parsing will always fail, and unit1 will always be 8.'
                                   //is to know if the method is called for adding a new item or for modifying an existing item.
                                   //Probably this could be changed, in just calling ItemSelected with the parameter unit = 1, always
                                   blength = FoodFile.getRecord(recid1,b,0);
                                   i1 = getfirstsemicolon();
                                   i1 = getnextsemicolon();
                                   i2 = getnextsemicolon();
                                   units[8] = new String(b,i1+1,i2-i1-1);
                                   try {
                                        unit1 = Integer.parseInt(units[8]);
                                   } catch (NumberFormatException ex) {
                                       //input contains a string, not an integer
                                       unit1 = 8;
                                   }
                                   
                                   //call additem
                                   HelpDiabetes.getitemfromuser.additem.ItemSelected(recid1,unit1,oldamount,shownrecid,unitnumber);
                            }
                        } catch (NumberFormatException nrex) {
                            ;//removed from old version, should not happen because we don't support own food item anymore
                            (new ReportException()).Report("NumberFormatException in ReadItemList.keyPressed - FIRE",nrex,false);
                        } catch (Exception ex) {
                             (new ReportException()).Report("Exception in ReadItemList.keyPressed - FIRE",ex,false);
                        }
                    }
                    break;
               default:;
            } // end switch statement
    }

        String GetClassName() {
        return("ReadItemList");
    }

    //overloading necessary to allow checking if user hits the first highlighted line
    protected void pointerPressed(int x, int y) {
        //boundaries in which x and y should fall to say that first line is hit
        int y_start;
        int y_end;

        y_start = fonthght; //Items found:
        y_start = y_start + 1;//horizontal line
        y_end = y_start + fonthght;

        if ((y_start - 1) < y && y < y_end) {
            keyPressed(Key_code_FIRE);
        } else {
            super.pointerPressed(x, y);
        }
    }



}
